package com.usian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.mapper.AuthMapper;
import com.usian.mapper.RoleMapper;
import com.usian.mapper.UserMapper;
import com.usian.pojo.Auth;
import com.usian.pojo.Role;
import com.usian.pojo.User;

import com.usian.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AuthMapper authMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /**
         * 1:根据用户名查询用户对象
         * 2：根据用户id 查询该用户拥有那些角色
         * 3：根据角色id 查询该用户有那些权限
         * 4：封装到 security auth 对象中  交给security管理
         *
         */

        //创建集合用来存放权限信息，并保存到集合中
        Collection<GrantedAuthority> authorities = new ArrayList<>();

        QueryWrapper<User> queryWrapper =new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername,username);
        List<User> userList = userMapper.selectList(queryWrapper);
        User user =null;
        if(userList.size()>0){
            user = userList.get(0);
        }

        //判断对象不能为空
        if(user ==null){
            return null;
        }

        //获取该用户的角色列表
        List<Role> roleList = roleMapper.findByUserId(user.getId());
        for(Role role :roleList){
            //ROLE_admin   ROLE_sale
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }


        //获取权限列表
        List<Auth> authList = authMapper.findByUserId(user.getId());
        for (Auth auth : authList) {
            authorities.add(new SimpleGrantedAuthority(auth.getName()));
        }

        //创建代表当前用户的User对象
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                .authorities(authorities).build();

        return userDetails;
    }

}
